import json
import time
import random

from RedisClient import RedisClientAdsl

import requests


class ADSL(object):
    r = RedisClientAdsl()

    def init(self, count):
        for i in range(count):
            res = requests.get(
                'http://api.tianqiip.com/getip?secret=ay0bqsbf86tolc8j&type=json&num=1&time=3&ts=1&port=1')
            if res.status_code == 200:
                print(json.loads(res.content))
                data = json.loads(res.content)
                for item in data['data']:
                    data = {
                        'ip': item['ip'],
                        'port': item['port'],
                        'expire': str(int(self.timestr2int(item['expire'])))+'-'+self.randoms()
                    }
                    self.r.setADSL(data)

    def randoms(self):
        strings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
        random_str = ''.join(random.sample(strings, 3))
        return random_str

    def timestr2int(self, timestr):
        return time.mktime(time.strptime(timestr, '%Y-%m-%d %H:%M:%S'))

    def DelOneAdsl(self, key):
        self.r.client.hdel('adsl_tianqi', key)

    def reflash(self):
        self.init(1)

    def scan(self):
        now = int(time.time())
        keys = self.r.client.hkeys('adsl_tianqi')
        for key in keys:
            data = str(key, encoding='utf-8')
            expire = data.split('-')[0]
            if now > int(expire) - 10:
                print(key)
                self.r.client.hdel('adsl_tianqi', key)


if __name__ == '__main__':
    bot = ADSL()
    bot.init(3)
    while True:
        bot.scan()
        time.sleep(1)
